<template>
  <div>
    <a-row :gutter="10">
      <!-- 昨日大盘投诉量 -->
      <a-col :span="5">
        <a-card :bordered="false">
          <a-row class="cardTitle">昨日大盘投诉量</a-row>
          <a-row>
            <a-col :span="6" class="cardContent">{{ data.lastDapanFeedback }}</a-col>
            <a-col :span="6" class="cardContent1" v-if="data.lastDapanFeedbackRate >= 0">{{ "↑ " + data.lastDapanFeedbackRate + "%" }}</a-col>
            <a-col :span="6" class="cardContent2" v-if="data.lastDapanFeedbackRate < 0">{{ "↓ " + data.lastDapanFeedbackRate + "%" }}</a-col>
          </a-row>
        </a-card>
      </a-col>
      <!-- 昨日投诉量 -->
      <a-col :span="5">
        <a-card>
          <a-row class="cardTitle">昨日投诉量</a-row>
          <a-row>
            <a-col :span="4" class="cardContent">{{ data.lastFeedback }}</a-col>
<!--            <a-col :span="6" class="cardContent1" v-if="data.lastFeedbackRate >= 0">{{ "↑ " + data.lastFeedbackRate + "%" }}</a-col>-->
<!--            <a-col :span="6" class="cardContent2" v-if="data.lastFeedbackRate < 0">{{ "↓ " + data.lastFeedbackRate + "%" }}</a-col>-->
          </a-row>
        </a-card>
      </a-col>
      <!-- 昨日归属投诉量 -->
      <a-col :span="5">
        <a-card :bordered="false">
          <a-row class="cardTitle">昨日归属投诉量</a-row>
          <a-row>
            <a-col :span="4" class="cardContent">{{ data.lastFeedbackBelong }}</a-col>
            <a-col :span="6" class="cardContent1" v-if="data.lastFeedbackBelongRate >= 0">{{ "↑ " + data.lastFeedbackBelongRate + "%" }}</a-col>
            <a-col :span="6" class="cardContent2" v-if="data.lastFeedbackBelongRate < 0">{{ "↓ " + data.lastFeedbackBelongRate + "%" }}</a-col>
          </a-row>
        </a-card>
      </a-col>
      <!-- 本月投诉量 -->
      <a-col :span="5">
        <a-card :bordered="false">
          <a-row class="cardTitle">本月投诉量</a-row>
          <a-row>
            <a-col :span="4" class="cardContent">{{ data.thisMonthFeedback }}</a-col>
            <a-col :span="6" class="cardContent1" v-if="data.thisMonthFeedbackRate >= 0">{{ "↑ " + data.thisMonthFeedbackRate + "%" }}</a-col>
            <a-col :span="6" class="cardContent2" v-if="data.thisMonthFeedbackRate < 0">{{ "↓ " + data.thisMonthFeedbackRate + "%" }}</a-col>
          </a-row>
        </a-card>
      </a-col>
      <!-- 本季度投诉量 -->
      <a-col :span="4">
        <a-card :bordered="false">
          <a-row class="cardTitle">本季度投诉量</a-row>
          <a-row>
            <a-col :span="6" class="cardContent">{{ data.thisQuarterFeedback }}</a-col>
            <a-col :span="7" class="cardContent1" v-if="data.thisQuarterFeedbackRate >= 0">{{ "↑ " + data.thisQuarterFeedbackRate + "%" }}</a-col>
            <a-col :span="7" class="cardContent2" v-if="data.thisQuarterFeedbackRate < 0">{{ "↓ " + data.thisQuarterFeedbackRate + "%" }}</a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="10" style="margin-top: 20px">
      <a-col :span="12">
        <a-card :bordered="false" title="每天大盘投诉量">
          <template #extra>
            <a-button type="link" @click="handleQuickSelect('7')">7天</a-button>
            <a-button type="link" @click="handleQuickSelect('15')">15天</a-button>
            <a-range-picker
                v-model:value="dateRange"
                @change="handleDapanDateChange"
                format="YYYY-MM-DD"
            />
          </template>
          <div id="dapanLine" class="xn-ht200"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card :bordered="false" title="我的投诉量">
          <template #extra>
            <a-button type="link" @click="handleQuickSelect2('7')">7天</a-button>
            <a-button type="link" @click="handleQuickSelect2('15')">15天</a-button>
            <a-range-picker
                v-model:value="dateRange2"
                @change="handleTousuDateChange"
                format="YYYY-MM-DD"
            />
          </template>
          <div id="wodeLine" class="xn-ht200"></div>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="10" style="margin-top: 20px">
      <a-col :span="24">
        <a-card :bordered="false" title="号码列表"  :style="{ paddingTop: '0'}" class="haomaCard">
          <template #extra>
            <a-input-search placeholder="输入号码搜索"  v-model:value="haomaPar" enter-button @search="haomaSearch" />
          </template>
          <s-table
              ref="tableRef"
              :columns="haomaCol"
              :data="loadHaomaData"
              bordered
              :row-key="(record) => record.complainant_number"
              :scroll="{ y: 240 }">
          </s-table>
        </a-card>
      </a-col>
    </a-row>
  </div>

</template>

<script setup name="indexHome">
import {onMounted} from "vue";
import {Line} from "@antv/g2plot";
import dayjs from 'dayjs';
import { reactive } from 'vue';
import tousuApi from "@/api/biz/tousuApi";
import orgApi from "@/api/sys/orgApi";
const data = reactive({
  lastDapanFeedback: 0,
  lastDapanFeedbackRate: 0,
  lastFeedback: 0,
  lastFeedbackRate: 0,
  lastFeedbackBelong: 0,
  lastFeedbackBelongRate: 0,
  thisMonthFeedback: 0,
  thisMonthFeedbackRate: 0,
  thisQuarterFeedback: 0,
  thisQuarterFeedbackRate: 0
});
let dapanLine = null;
let tousuLine = null;
const haomaData = ref([]);
const haomaPar = ref('');
const tableRef = ref(null)
const dateRange = ref([]);
const dateRange2 = ref([]);
const haomaCol = [
  {
    dataIndex: 'phaoma',
    title: '号码',
  },
  {
    title: '昨日投诉量',
    dataIndex: 'yest_cnt',
  },
  {
    title: '昨日投诉量同比',
    dataIndex: 'yest_rate',
    customRender: ({ text }) => {
      if (text == null || text === '') {
        return '-';
      }
      const rate = parseFloat(text);
      const color = rate >= 0 ? '#e30707' : '#33a84a';
      const symbol = rate >= 0 ? '↑' : '↓';
      return h('span', { style: { color } }, `${symbol} ${Math.abs(rate).toFixed(2)}%`);
    }
  },
  {
    title: '本月投诉量',
    dataIndex: 'month_cnt',
  },
  {
    title: '本月投诉量同比',
    dataIndex: 'month_rate',
    customRender: ({ text }) => {
      if (text == null || text === '') {
        return '-';
      }
      const rate = parseFloat(text);
      const color = rate >= 0 ? '#e30707' : '#33a84a';
      const symbol = rate >= 0 ? '↑' : '↓';
      return h('span', { style: { color } }, `${symbol} ${Math.abs(rate).toFixed(2)}%`);
    }
  },
  {
    title: '本月投诉量（归属）',
    dataIndex: 'month_be_cnt',
  },
  {
    title: '本季度投诉量',
    dataIndex: 'quarter_cnt',
  },
  {
    title: '本季度投诉量同比',
    dataIndex: 'quarter_rate',
    customRender: ({ text }) => {
      if (text == null || text === '') {
        return '-';
      }
      const rate = parseFloat(text);
      const color = rate >= 0 ? '#e30707' : '#33a84a';
      const symbol = rate >= 0 ? '↑' : '↓';
      return h('span', { style: { color } }, `${symbol} ${Math.abs(rate).toFixed(2)}%`);
    }
  },
  {
    title: '本季度投诉量（归属）',
    dataIndex: 'quarter_be_cnt',
  }
];
const handleQuickSelect = async (type) => {
  let startDate, endDate;
  switch(type) {
    case '1':
      startDate = dayjs().startOf('day');
      endDate = dayjs().endOf('day');
      break;
    case '7':
      startDate = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
      endDate = dayjs().format('YYYY-MM-DD');
      break;
    case '15':
      startDate = dayjs().subtract(15, 'day').format('YYYY-MM-DD');
      endDate = dayjs().format('YYYY-MM-DD');
      break;
  }
  dateRange.value = [dayjs(startDate), dayjs(endDate)];
  await handleDapanDateChange()
};
const handleQuickSelect2 = async (type) => {
  let startDate, endDate;
  switch(type) {
    case '1':
      startDate = dayjs().startOf('day');
      endDate = dayjs().endOf('day');
      break;
    case '7':
      startDate = dayjs().subtract(7, 'day').format('YYYY-MM-DD');
      endDate = dayjs().format('YYYY-MM-DD');
      break;
    case '15':
      startDate = dayjs().subtract(15, 'day').format('YYYY-MM-DD');
      endDate = dayjs().format('YYYY-MM-DD');
      break;
  }
  dateRange2.value = [dayjs(startDate), dayjs(endDate)];
  await handleTousuDateChange()
};
const haomaSearch = (value) => {
  haomaPar.value = value;
  loadHaomaData()
  tableRef.value?.refresh();
}
const loadHaomaData = () => {
  let data = {
    searchKey: haomaPar.value
  }
  return tousuApi.getTousuNumberList(data).then((res) => {
    console.log("res",res.tousuNumberList)
    return {
      records: res.tousuNumberList,
      total: res.tousuNumberList.length,
      success: true
    };
  })
}
const handleDapanDateChange = async () => {
  try {
    let startDate = dateRange.value[0] ? dateRange.value[0].format('YYYY-MM-DD') : '';
    let endDate = dateRange.value[1] ? dateRange.value[1].format('YYYY-MM-DD') : '';
    console.log("startDate",startDate,'endDate',endDate)
    let data = {
      startDate: startDate,
      endDate: endDate
    }
    const res = await tousuApi.getDapanData(data);

    const dapanData = res.dapanData.map(item => ({
      date: item.record_date,
      value: item.ts_amount
    }));
    if (dapanLine){
      dapanLine.destroy();
    }
    console.log("dapanData",dapanData)
    dapanLine = new Line('dapanLine', {
      data: dapanData,
      height: 200,
      width: '100%',
      xField: 'date',
      yField: 'value',
      xAxis: {
        type: 'cat', // 分类类型
        label: {
          style: {
            fontSize: 12,
          }
        }
      },
      yAxis: {
        label: {
          formatter: (v) => `${v}`,
          style: {
            fontSize: 12,
          }
        }
      },
      smooth: true,
      color: '#1677FF',
      lineStyle: {
        lineWidth: 3
      },
      point: {
        size: 4,
        shape: 'circle',
        style: {
          fill: 'white',
          stroke: '#1677FF',
          lineWidth: 2
        }
      }
    })
    dapanLine.render();
  } catch (error) {
    console.error('获取首页数据失败:', error);
  }
}
const handleTousuDateChange = async () => {
  try {
    let startDate = dateRange2.value[0] ? dateRange2.value[0].format('YYYY-MM-DD') : '';
    let endDate = dateRange2.value[1] ? dateRange2.value[1].format('YYYY-MM-DD') : '';
    console.log("startDate",startDate,'endDate',endDate)
    let data = {
      startDate: startDate,
      endDate: endDate
    }
    const res = await tousuApi.getTousuData(data);

    const dapanData = res.tousuData.map(item => ({
      date: item.record_date,
      value: item.ts_amount
    }));
    if (tousuLine){
      tousuLine.destroy();
    }
    console.log("dapanData",dapanData)
    tousuLine = new Line('wodeLine', {
      data: dapanData,
      height: 200,
      width: '100%',
      xField: 'date',
      yField: 'value',
      xAxis: {
        type: 'cat', // 分类类型
        label: {
          style: {
            fontSize: 12,
          }
        }
      },
      yAxis: {
        label: {
          formatter: (v) => `${v}`,
          style: {
            fontSize: 12,
          }
        }
      },
      smooth: true,
      color: '#1677FF',
      lineStyle: {
        lineWidth: 3
      },
      point: {
        size: 4,
        shape: 'circle',
        style: {
          fill: 'white',
          stroke: '#1677FF',
          lineWidth: 2
        }
      }
    })
    tousuLine.render();
  } catch (error) {
    console.error('获取首页数据失败:', error);
  }
}
// 获取后端请求
const loadData = async () => {
  try {
    const res = await tousuApi.getIndexData();
    if (res) {
      Object.assign(data, res.data || res);
      console.log("data",data)
    }
  } catch (error) {
    console.error('获取首页数据失败:', error);
  }
};
// 号码列表

const init = () => {
  // 线型图初始化
  dateRange.value = [dayjs().subtract(8, 'day'), dayjs().subtract(1, 'day')];
  dateRange2.value = [dayjs().subtract(8, 'day'), dayjs().subtract(1, 'day')];
  handleDapanDateChange();
  handleTousuDateChange()
}
onMounted(() => {
  loadData()
  init()
  // 号码列表初始化
  // getTousuNumberList()
})
</script>
<style scoped>
.cardTitle {
  font-size: 16px;
  color: #8f8f8f;
}
.cardContent {
  font-size: 24px;
  color: #1c1c1c;
}
.cardContent1 {
  font-size: 18px;
  color: #e30707;
}
.cardContent2 {
  font-size: 18px;
  color: #33a84a;
}
.haomaCard{
  padding: 0;
}
:deep(.haomaCard .ant-card-body) {
  padding: 0 24px !important;
}
</style>
